package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 菜单menu控制层
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    private UserService userService;

    @RequestMapping("/getMenuByUserName")
    public Result getMenuByUserName(String username){
        User user = userService.findByUsername(username);
        if(user ==null){
            return null;
        }
        Set<Role> roles = user.getRoles();
        //创建一个去除重复集合存储菜单集合(考虑到一个用户有多个角色,一个角色有多种菜单)
        LinkedHashSet<Map> Menulist = new LinkedHashSet<>();
        for (Role role : roles) {
            //拿到菜单
            LinkedHashSet<Menu> menus = role.getMenus();
            //遍历菜单集合
            for (Menu menu : menus) {
                //创建父菜单map
                HashMap<String, Object> menumap = new HashMap<>();
                String path = menu.getPath();
                String title = menu.getName();
                String icon = menu.getIcon();

                menumap.put("path",path);
                menumap.put("title",title);
                menumap.put("icon",icon);

                List<Menu> children = menu.getChildren();
                //如果没有相关子菜单则为空
                if(children==null){
                    menumap.put("children",children);
                }
                //创建新的子菜单集合来存储相关子菜单
                List<Map> sonlist = new ArrayList<>();
                for (Menu child : children) {
                    HashMap<String, Object> sonmap = new HashMap<>();
                    sonmap.put("path",child.getPath());
                    sonmap.put("title",child.getName());
                    sonmap.put("linkUrl",child.getLinkUrl());
                    sonmap.put("children",child.getChildren());
                    sonlist.add(sonmap);
                }
                //将子菜单塞进父菜单中
                menumap.put("children",sonlist);
                Menulist.add(menumap);
            }

        }
        return new Result(true, MessageConstant.GET_MENU_SUCCESS,Menulist);
    }

}
